<template>
    <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()" style="margin-top: 10px;">
        <div class="grid-container">
            <el-form-item label="产品编号">
                <el-input v-model="state.dataForm.seriesCode" type="text" clearable placeholder="请输入产品编号"></el-input>
            </el-form-item>
            <el-form-item label="系列名称">
                <el-input v-model="state.dataForm.seriesName" type="text" clearable placeholder="请输入系列名称"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
              <el-input v-model="state.dataForm.brandName" type="text" clearable placeholder="请输入品牌"></el-input>
            </el-form-item>
            <el-form-item label="产品分类" prop="selectedClassPath">
              <el-cascader :options="classOptions" clearable
                           :props="cascaderProps"
                           :show-all-levels="false"
                           v-model="selectedClassPath"
                           @change="handleClassChange"></el-cascader>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="selectedStatus" placeholder="请选择状态" clearable multiple @change="handleStatusChange">
                    <el-option :label="'上架'" :value="0"></el-option>
                    <el-option :label="'下架'" :value="1"></el-option>
                    <el-option :label="'停产'" :value="2"></el-option>
                    <el-option :label="'待审核'" :value="3"></el-option>
                </el-select>
            </el-form-item>
        </div>
        <div class="form">
            <div style="display: flex;">
                <el-form-item label="价格区间">
                    <el-input v-model="state.dataForm.minQuotation" type="number" placeholder="最低价" style="width: 120px;" clearable></el-input>
                </el-form-item>
                <span style="margin-top: 5px;margin-left: -4px;">___</span>
                <el-form-item label-width="10px">
                    <el-input v-model="state.dataForm.maxQuotation" type="number" placeholder="最高价" style="width: 120px;margin-left: 10px;" clearable></el-input>
                </el-form-item>
              <span style="margin: 0 10px;"></span>
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="state.dataForm.createAtStart"
                  type="datetime"
                  placeholder="开始时间"
                  style="width: 200px;"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  clearable
                />
                <span style="margin: 0 10px;">——</span>
                <el-date-picker
                  v-model="state.dataForm.createAtEnd"
                  type="datetime"
                  placeholder="结束时间"
                  style="width: 200px;"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :default-time="new Date(0,0,0,23,59,59)"
                  clearable
                />
              </el-form-item>
            </div>
          <div>
                <!-- 查询 -->
                <el-form-item>
                    <el-button @click="queryData"
                        style="background: rgba(22, 119, 255, 1);color: #fff;border-radius: 5px;">{{
                            $t("query") }}</el-button>
                </el-form-item>
                <!-- 重置 -->
                <el-form-item>
                    <el-button @click="resetForm"
                        style="background: rgba(239, 244, 255, 1);border: 1px solid rgba(16, 98, 202, 1);color: #1062CA;border-radius: 5px;">重置</el-button>
                </el-form-item>
                <!--新增-->
                <el-form-item>
                    <el-button @click="addOrUpdateHandle()" v-if="state.hasPermission('noc:productseries:save')"
                        style="background: rgba(22, 119, 255, 1);color: #fff;width: 100px;border-radius: 5px;">新增产品</el-button>
                </el-form-item>
            </div>
        </div>
        <el-table :header-cell-style="{ 'background': '#eef1f6', 'color': '#1f2d3d', 'border-color': '#dfe6ec' }"
            v-loading="state.dataListLoading" :data="state.dataList" border
            @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
            <el-table-column align="center" prop="seriesCode" label="产品编号" width="180" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="seriesName" label="系列名称" width="150" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="brandName" label="品牌" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="className" label="分类" width="280" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="productCount" label="型号数量" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="userCount" label="供应商数量" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" label="价格区间" width="180" show-overflow-tooltip>
              <template v-slot="scope">
                <span v-if="scope.row.minQuotation || scope.row.maxQuotation">
                    <span v-if="scope.row.minQuotation === scope.row.maxQuotation">
                      {{ scope.row.maxQuotation }}
                    </span>
                    <span v-else>
                      {{ scope.row.minQuotation }} -- {{ scope.row.maxQuotation }}
                    </span>
                  </span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="collectCount" label="收藏数量" width="100" show-overflow-tooltip></el-table-column>

            <el-table-column align="center" prop="createAt" label="创建时间" width="180" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" prop="createUsername" label="创建人" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="updateUsername" label="更新人" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="updateAt" label="更新时间" width="180" show-overflow-tooltip></el-table-column>

          <el-table-column align="center" prop="auditTime" label="审核时间" width="180" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="auditName" label="审核人" width="180" show-overflow-tooltip></el-table-column>
          <el-table-column fixed="right" align="center" label="产品状态" width="100" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.ifValid === 0" style="color: #67C23A">上架</span>
              <span v-else-if="scope.row.ifValid === 1" style="color: #F56C6C">下架</span>
              <span v-else-if="scope.row.ifValid === 2" style="color: #909399">停产</span>
              <span v-else-if="scope.row.ifValid === 3" style="color: #F56C6C">待审核</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right"  align="center" prop="audit" label="审核状态" width="100" show-overflow-tooltip>
            <template v-slot="scope">
              <span v-if="scope.row.audit === 0" style="color: #F56C6C">待审核</span>
              <span v-else-if="scope.row.audit === 1" style="color: #67C23A">已通过</span>
              <span v-else-if="scope.row.audit === 2" style="color: #F56C6C">已驳回</span>
            </template>
          </el-table-column>
            <el-table-column fixed="right" align="center" prop="readOnly" label="操作" width="260">
              <template v-slot="scope">
                <el-button link type="primary" @click="editHandle(scope.row.id)" v-if="state.hasPermission('noc:productseries:update')">{{ $t("编辑")}}</el-button>
                <el-button link type="danger" v-if="state.hasPermission('noc:productseries:delete')" @click="deleteHandle(scope.row.id)">删除</el-button>
                <el-button  link style="color: rgba(56, 56, 56, 1);" @click="check(scope.row.id)">查看</el-button>
                <el-button  link type="primary" @click="audit(scope.row.id)" v-if="scope.row.audit !== 1 && state.hasPermission('noc:productseries:audit')">审核</el-button>
                <el-button v-if="scope.row.ifValid!== 0 && scope.row.audit === 1 && state.hasPermission('noc:productseries:down ')" link type="primary" @click="upHandle(scope.row.id)">上架</el-button>
                <el-button v-if="scope.row.ifValid!== 1 && scope.row.audit === 1 && state.hasPermission('noc:productseries:down')" link type="danger" @click="downHandle(scope.row.id)">下架</el-button>
                <el-button v-if="scope.row.ifValid!== 2 && scope.row.audit === 1 && state.hasPermission('noc:productseries:down ')" link type="info"  @click="stopHandle(scope.row.id)">停产</el-button>
              </template>
            </el-table-column>
        </el-table>
    </el-form>
    <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
        :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle"
        @current-change="state.pageCurrentChangeHandle"> </el-pagination>

</template>
<script lang="ts" setup>
import { onActivated } from 'vue'
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus"
import { useRoute, useRouter } from "vue-router";
import useView from "@/hooks/useView";
import { nextTick, reactive, ref, toRefs, onMounted, onBeforeUnmount } from "vue";
import router from "@/router";
const view = reactive({
  getDataListURL: '/noc/productseries/list',
  getDataListIsPage: true,
  deleteURL: "/noc/productseries/delete",
  deleteIsBatch: true,
  dataForm: {
    id: "",
    seriesCode: "",
    seriesName: "",
    brandName: "",
    class1Id: "",
    class2Id: "",
    class3Id: "",
    ifValids: "",
    minPrice: "",
    maxPrice: "",
    minQuotation: "",
    maxQuotation: "",
    createAtStart:"",
    createAtEnd:"",
  },
});
onActivated(() => {
  const from = router.options.history.state.back as string
  if (from && from.includes('nocproduct-list-add-or-update')) {
    state.getDataList()
  }
   if (from && from.includes('nocproduct-view-audit')) {
    state.getDataList()
  }
})

// 分类选项
const classOptions = ref<any[]>([]);
// 选中的分类路径
const selectedClassPath = ref<string[]>([]);
// 状态多选值
const selectedStatus = ref([]);
// 修改 props 为 cascaderProps
const cascaderProps = reactive({ value: "id", label: "className", children: "children", emitPath: true });

// 处理状态多选变化
const handleStatusChange = (value: any[]) => {
  // 将数组转换为逗号分隔的字符串
  state.dataForm.ifValids = value.length > 0 ? value.join(',') : '';
};

// // 重置表单
// const resetForm = () => {
//     view.dataForm.id = "";
//     view.dataForm.seriesCode = "";
//     view.dataForm.seriesName = "";
//     view.dataForm.brandName = "";
//     view.dataForm.class1Id = "";
//     view.dataForm.class2Id = "";
//     view.dataForm.class3Id = "";
//     view.dataForm.ifValids = "";
//     view.dataForm.minQuotation = "";
//     view.dataForm.maxQuotation = "";
//     // 重置状态多选值
//     selectedStatus.value = [];
//     // 新增：重置级联选择器的值
//     selectedClassPath.value = [];
//     state.getDataList();
// };

// 替换原有的删除按钮点击处理
const deleteHandle = (id: number) => {
  state.deleteHandle(id).then(() => {
    // 删除成功后只刷新数据列表，不重置表单
    state.getDataList();
  });
};

// 修改查询按钮的点击处理
const queryData = () => {
  saveCurrentQuery();
  state.page = 1; // 重置页码到第一页
  state.getDataList();
};

// 修改重置方法以清除保存的查询条件
const resetForm = () => {
  view.dataForm.id = "";
  view.dataForm.seriesCode = "";
  view.dataForm.seriesName = "";
  view.dataForm.brandName = "";
  view.dataForm.class1Id = "";
  view.dataForm.class2Id = "";
  view.dataForm.class3Id = "";
  view.dataForm.ifValids = "";
  view.dataForm.minQuotation = "";
  view.dataForm.maxQuotation = "";
  view.dataForm.createAtStart = "";
  view.dataForm.createAtEnd = "";
  // 重置状态多选值
  selectedStatus.value = [];
  // 重置级联选择器的值
  selectedClassPath.value = [];
  // 清除保存的查询条件
  sessionStorage.removeItem('nocproductListQuery');
  state.page = 1; // 重置页码到第一页
  state.getDataList();
};

// 在执行查询前保存当前查询条件
const saveCurrentQuery = () => {
  const query = {
    dataForm: { ...state.dataForm },
    selectedStatus: [...selectedStatus.value],
    selectedClassPath: [...selectedClassPath.value]
  };
  sessionStorage.setItem('nocproductListQuery', JSON.stringify(query));
};

// 编辑产品系列
const editHandle = (id: number) => {
  saveCurrentQuery(); // 保存当前查询条件
  router.push({
    path: "/program/nocproduct-list-add-or-update",
    query: {
      id,
      from: "/program/nocproduct-list"
    }
  });
};

// 跳转新增产品系列页面
const addOrUpdateHandle = () => {
  saveCurrentQuery(); // 保存当前查询条件
  router.push({
    path: "/program/nocproduct-list-add-or-update",
    query: {
      from: "/program/nocproduct-list"
    }
  });
};

// 跳转查看页面
const audit = (id: number) => {
    router.push({
        path: "/program/nocproduct-view-audit",
        query: { id }
    });
};
// 跳转查看页面
const check = (id: number) => {
    router.push({
        path: "/program/nocproduct-view",
        query: {
          id,
          from: "/program/nocproduct-list"
        }
    });
};

// 上架
const upHandle = (id: number) => {
    baseService.post('/noc/productseries/up', { id }).then(res => {
        if (res && res.code === 0) {
            ElMessage.success('上架成功');
            state.refreshDataList()
        } else {
            ElMessage.error(res.msg);
        }
    });
};

// 下架
const downHandle = (id: number) => {
    baseService.post('/noc/productseries/down', { id }).then(res => {
        if (res && res.code === 0) {
            ElMessage.success('下架成功');
             state.refreshDataList()
        } else {
            ElMessage.error(res.msg);
        }
    });
};

// 停产
const stopHandle = (id: number) => {
    baseService.post('/noc/productseries/stop', { id }).then(res => {
        if (res && res.code === 0) {
            ElMessage.success('停产成功');
             state.refreshDataList()
        } else {
            ElMessage.error(res.msg);
        }
    });
};

const handleClassChange = (value: string[]) => {
  state.dataForm.class1Id = value && value.length > 0 ? value[0] : "";
  state.dataForm.class2Id = value && value.length > 1 ? value[1] : "";
  state.dataForm.class3Id = value && value.length > 2 ? value[2] : "";
};

// 获取分类列表
const getClassList = () => {
  baseService.get('/noc/nocclassify/list2').then(res => {
    // 确保数据结构符合级联选择器要求
    classOptions.value = res.data;
    console.log('分类数据加载成功:', classOptions.value);
  }).catch(error => {
    console.error('获取分类数据出错:', error);
    ElMessage.error('获取分类数据出错');
  });
};


const state = reactive({ ...useView(view), ...toRefs(view) });
state.limit = 20;

const route = useRoute();

// 在页面加载时检查是否有缓存的查询条件
onMounted(() => {
  getClassList();

  // 检查是否是从编辑页面返回
  if (route.query.fromEdit === 'true') {
    // 从编辑页面返回，恢复查询条件
    const savedQuery = sessionStorage.getItem('nocproductListQuery');
    if (savedQuery) {
      try {
        const query = JSON.parse(savedQuery);
        Object.assign(state.dataForm, query.dataForm);
        selectedStatus.value = query.selectedStatus || [];
        selectedClassPath.value = query.selectedClassPath || [];
        // 使用nextTick确保DOM更新后再获取数据
        nextTick(() => {
          state.getDataList();
        });
      } catch (e) {
        console.error('解析查询条件失败', e);
        state.getDataList();
      }
    } else {
      state.getDataList();
    }
  } else {
    // 不是从编辑页面返回，清除之前的查询条件
    sessionStorage.removeItem('nocproductListQuery');
    state.getDataList();
  }
});

// 在页面卸载时清除搜索条件
onBeforeUnmount(() => {
  sessionStorage.removeItem('nocproductListQuery');
});

</script>
<style lang="scss" scoped>
::v-deep .el-table .cell {
    white-space: nowrap;
}

.el-input {
    width: 218px;
    height: 32px;
    opacity: 1;
    border-radius: 5px;
    background: rgba(255, 255, 255, 1);
}

.form {
    display: flex;
    justify-content: space-between;
}
.grid-container{
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); /* 自动适应列宽，每列至少200px */
    gap: 16px; /* 元素间距 */
}
</style>
